package com.jtjrenren.android.taxi.passenger.core.main;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.jtjrenren.android.taxi.passenger.core.order.history.OrderHistoryActivity;
import com.jtjrenren.android.taxi.passenger.core.order.place.PlaceChooseActivity;
import com.jtjrenren.android.taxi.passenger.core.setting.config.SettingActivity;
import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.core.order.status.OrderStatusActivity;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.base.BaseMvpActivity;
import com.jtjrenren.android.taxi.passenger.bean.ApiCarListArea;
import com.jtjrenren.android.taxi.passenger.bean.User;
import com.jtjrenren.android.taxi.passenger.bean.AddressInfo;
import com.jtjrenren.android.taxi.passenger.bean.Order;
import com.jtjrenren.android.taxi.passenger.core.order.disptach.OrderPreStatusActivity;
import com.jtjrenren.android.taxi.passenger.core.user.login.UserLoginActivity;
import com.jtjrenren.android.taxi.passenger.core.wallect.main.WallectActivity;
import com.jtjrenren.android.taxi.passenger.manger.AppManger;
import com.jtjrenren.android.taxi.passenger.core.setting.about.AboutActivity;
import com.jtjrenren.android.taxi.passenger.core.order.account.OrderAccountChooseActivity;
import com.jtjrenren.android.taxi.passenger.core.order.date.OrderDateSelectDialogActivity;
import com.jtjrenren.android.taxi.passenger.core.order.tip.OrderTipChooseActivity;
import com.jtjrenren.android.taxi.passenger.core.user.details.UserDetailActivity;
import com.jtjrenren.android.taxi.passenger.utils.InitView;
import com.jtjrenren.android.taxi.passenger.utils.UIHelper;
import com.library.utils.DensityUtils;
import com.library.utils.LogUtil;
import com.library.utils.SpUtils;
import com.library.utils.StringUtils;
import com.jtjrenren.android.taxi.passenger.utils.ActivityIntentUtils;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;
import com.library.utils.AppUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

public class HomeActivity extends BaseMvpActivity<MainPresenter> implements MainView {
    private static final int REQUEST_CODE_START = 100;
    private static final int REQUEST_CODE_END = 101;
    private static final int REQUEST_CHOOSE_DATE = 102;
    private static final int REQUEST_CHOOSE_TIP = 103;
    private static final int REQUEST_CHOOSE_PHONE = 104;

    //菜单
    @BindView(R.id.indexmenu_user_name)
    TextView tv_user_name;
    @BindView(R.id.indexmenu_loginorout)
    TextView tv_loginout;

    //标题相关
    @BindView(R.id.title_right_tv)
    TextView tv_right;
    @BindView(R.id.home_menu)
    DrawerLayout dl_menu;

    //频道相关
    @BindView(R.id.channel_specar_channels)
    RelativeLayout ll_channels_specar;
    @BindView(R.id.channel_taxi)
    RadioButton rb_taxi;
    @BindView(R.id.channel_specar_soft)
    RadioButton cb_ssx;
    @BindView(R.id.channel_specar_business)
    RadioButton cb_swx;
    @BindView(R.id.channel_specar_haohua)
    RadioButton cb_hhx;
    @BindView(R.id.callcar_type_ss)
    RadioButton rb_ss;
    @BindView(R.id.index_bar_arrow)
    ImageView iv_arrow;
    @BindView(R.id.channel_specar)
    RadioButton rb_speacr;

    //百度地图u相关
    @BindView(R.id.indexcall_mapshow_map)
    MapView bdMapView;
    @BindView(R.id.indexcall_mapshow_loc)
    TextView tv_loc;

    //订单详情相关
    @BindView(R.id.orderdetails_conn)
    LinearLayout cll_order;
    @BindView(R.id.order_details_date)
    LinearLayout ll_date;
    @BindView(R.id.order_details_pay)
    LinearLayout ll_pay;
    @BindView(R.id.order_details_start_desc)
    TextView tv_start_desc;
    @BindView(R.id.order_details_end_desc)
    TextView tv_end_desc;
    @BindView(R.id.order_details_pay_desc)
    TextView tv_paydesc;
    @BindView(R.id.order_details_account_desc)
    TextView tv_account_desc;
    @BindView(R.id.order_details_date_desc)
    TextView tv_date_desc;
    @BindView(R.id.order_details_tip_desc)
    TextView tv_tip_desc;
    @BindView(R.id.carcall_call)
    Button bt_call;


    private BaiduMap bdMap;
    private BitmapDescriptor taxiMarker = BitmapDescriptorFactory
            .fromResource(R.mipmap.icon_taxi_marker);
    private BitmapDescriptor specarMarker = BitmapDescriptorFactory
            .fromResource(R.mipmap.icon_specar_marker);
    private List<Marker> carMarkerList;
    private int dip_35;
    private int dip_38;

    @Override
    public int getLayoutId() {
        return R.layout.aty_index;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.destory();
        if (taxiMarker != null)
            taxiMarker.recycle();
        if (specarMarker != null)
            specarMarker.recycle();
    }


    @Override
    protected void onPause() {
        super.onPause();
        dl_menu.closeDrawers();
    }


    @Override
    public void initM() {
        presenter.sub();
        carMarkerList = new ArrayList<>();

        dip_35 = DensityUtils.dip2px(this, 35);
        dip_38 = DensityUtils.dip2px(this, 46);

        bdMap = bdMapView.getMap();
        InitView.initBdmapView(bdMapView);
        UiSettings settings = bdMap.getUiSettings();
        settings.setAllGesturesEnabled(true);   //手势操作
        settings.setZoomGesturesEnabled(true);//获取是否允许缩放手势返回:是否允许缩放手势

        setListeners();

        showYyC((Boolean) SpUtils.getParam(this,"showyyc",false));

        presenter.initMain();


        rb_taxi.setChecked(true);

        rb_ss.setChecked(true);
    }

    @Override
    protected void onResume() {
        super.onResume();

        presenter.initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.INTENT_REQUEST_CODE_LOGIN:
                if (resultCode == RESULT_OK) {
                    refreshAfterLogin(AppManger.getInstance().user);
                }
                break;
            case REQUEST_CODE_START:
                if (resultCode == RESULT_OK) {
                    AddressInfo info = (AddressInfo) data.getExtras().get(PlaceChooseActivity.INTENT_DATA_ADDR);
                    presenter.startAddrChange(info);
                }
                break;
            case REQUEST_CODE_END:
                if (resultCode == RESULT_OK) {
                    AddressInfo info = (AddressInfo) data.getExtras().get(PlaceChooseActivity.INTENT_DATA_ADDR);
                    presenter.endAddrChange(info);
                }
                break;
            case REQUEST_CHOOSE_DATE:
                if (resultCode == RESULT_OK) {
                    String dateStr = data.getStringExtra("date");
                    presenter.dateChange(dateStr);
                }
                break;
            case REQUEST_CHOOSE_TIP:
                if (resultCode == RESULT_OK) {
                    String tip = data.getStringExtra(OrderTipChooseActivity.RETURN_VALUE);
                    presenter.tipChange(tip);
                }
                break;
            case REQUEST_CHOOSE_PHONE:
                if (resultCode == RESULT_OK) {
                    String phone = data.getStringExtra(OrderAccountChooseActivity.RETURN_VALUE);
                    presenter.phoneChange(phone);
                }
                break;
        }
    }


    @Override
    public void goWebPage(String title, String url, boolean showTitle) {
        ActivityIntentUtils.showHtmlActivity(this, url, title, showTitle);
    }

    @Override
    public void goLoginPage() {
        Intent intent = new Intent(this, UserLoginActivity.class);
        startActivityForResult(intent, Constants.INTENT_REQUEST_CODE_LOGIN);
    }

    @Override
    public void goPrePage(Order order) {
        Intent intent = new Intent(this, OrderPreStatusActivity.class);
        intent.putExtra(OrderPreStatusActivity.EXTRACT_ORDER, order);
        startActivity(intent);
    }

    @Override
    public void showTip(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoginOutView() {
        UIHelper.getAlertDialog(this, getString(R.string.querendengchu), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppManger.getInstance().loginOut();
                refreshAfterLogin(null);
                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    @Override
    public void showWaitingTip(String desc, boolean isCancle) {
        showWaittingDialog(desc, isCancle);
    }

    @Override
    public void dissWaitingTip() {
        dismissWaittingDialog();
    }

    @Override
    public void refreshAfterLogin(User user) {
        if (user != null) {
            tv_right.setVisibility(View.GONE);
            tv_user_name.setText(user.getPhone());
            tv_loginout.setText(R.string.loginout);
        } else {
            tv_right.setVisibility(View.VISIBLE);
            tv_user_name.setText(getString(R.string.qingxiandenglu));
            tv_loginout.setText(R.string.login);
        }
    }

    @Override
    public void refreshBdMapCenter(LatLng ll) {
        LogUtil.log("home", "通知地图刷新位置！");
        MapStatus.Builder builder = new MapStatus.Builder().target(ll).zoom(19);
        MapStatusUpdate update = MapStatusUpdateFactory.newMapStatus(builder.build());
        bdMap.animateMapStatus(update);
    }

    @Override
    public void refreshYgCost(String desc) {
        tv_paydesc.setText(desc);
    }

    @Override
    public void showGpsTip() {
        UIHelper.getAlertDialog(HomeActivity.this, getString(R.string.shifoukaiqigps), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppUtils.openGpsSetting(HomeActivity.this);
                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    @Override
    public void refreshStartMsg(String addrName) {
        tv_loc.setText(addrName);
        tv_start_desc.setText(addrName);
    }

    @Override
    public void refreshEndMsg(String addrName) {
        tv_end_desc.setText(addrName);

        if (bt_call.getVisibility() == View.GONE || bt_call.getVisibility() == View.INVISIBLE)
            bt_call.setVisibility(View.VISIBLE);
    }

    @Override
    public void refreshCfDate(String date) {
        tv_date_desc.setText(date);
    }

    @Override
    public void refreshTip(String tip) {
        tv_tip_desc.setText(tip + getString(R.string.yuan));
    }

    @Override
    public void refreshCoPhone(String desc) {
        tv_account_desc.setText(desc);
    }

    @Override
    public void refreshCarListOnMap(int type, List<ApiCarListArea.CarListEntity> list) {
        BitmapDescriptor bitmapDescriptor = null;

        if (type == Constants.CARTYPE_TAXI)
            bitmapDescriptor = taxiMarker;
        else
            bitmapDescriptor = specarMarker;

        LatLng target;
        MarkerOptions option = new MarkerOptions().icon(bitmapDescriptor).draggable(false);

        for (ApiCarListArea.CarListEntity info : list) {
            target = new LatLng(Double.parseDouble(info.getLatitude()), Double.parseDouble(info.getLongitude()));
            option.position(target);
            carMarkerList.add((Marker) bdMap.addOverlay(option));
        }
    }

    @Override
    public void clearCarListOnMap() {
        if (carMarkerList == null)
            return;
        for (Marker marker : carMarkerList)
            marker.remove();
        carMarkerList.clear();
    }

    @Override
    public void selectTaxiType() {
        showSpecarChannels(false);
        iv_arrow.setVisibility(View.GONE);
        bt_call.setText(R.string.hujiaochuzuche);
    }

    @Override
    public void selectSpeCar() {
        showSpecarChannels(true);
        iv_arrow.setVisibility(View.VISIBLE);
        cb_ssx.setChecked(true);
        bt_call.setText(R.string.hujiaoyuezuche);
    }

    @Override
    public void showSpecarChannels(boolean isShow) {
        if (isShow) {
            if (ll_channels_specar.getVisibility() == View.VISIBLE)
                return;
            ll_channels_specar.setVisibility(View.VISIBLE);
            changeHeight(ll_channels_specar, 0.0f, 1.0f, dip_35, null);
        } else {
            if (ll_channels_specar.getVisibility() == View.GONE)
                return;
            changeHeight(ll_channels_specar, 1.0f, 0.0f, dip_35, new ChangeEndListner() {
                @Override
                public void end() {
                    ll_channels_specar.setVisibility(View.GONE);
                }
            });
        }
    }

    @Override
    public void showYyView(boolean isShow) {
        if (isShow) {
            if (ll_date.getVisibility() == View.VISIBLE)
                return;
            ll_date.setVisibility(View.VISIBLE);
            changeHeight(ll_date, 0.0f, 1.0f, dip_38, null);
        } else {
            if (ll_date.getVisibility() == View.GONE)
                return;
            changeHeight(ll_date, 1.0f, 0.0f, dip_38, new ChangeEndListner() {
                @Override
                public void end() {
                    ll_date.setVisibility(View.GONE);
                }
            });
        }
    }

    @Override
    public void showYyC(boolean isShow) {
        if (isShow){
            rb_speacr.setVisibility(View.VISIBLE);
        }else {
            rb_speacr.setVisibility(View.GONE);
        }
    }


    @Override
    public void showNotFinishOrder(String desc, final String data) {
        UIHelper.getAlertDialog(HomeActivity.this, desc, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(HomeActivity.this, OrderStatusActivity.class);
                intent.putExtra(OrderStatusActivity.EXTRA_ORDERSERNO, data);
                startActivity(intent);
                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();
    }

    @Override
    public void showSpecarPayView(boolean isShow) {
        if (isShow) {
            if (ll_pay.getVisibility() == View.VISIBLE)
                return;
            ll_pay.setVisibility(View.VISIBLE);
            changeHeight(ll_pay, 0.0f, 1.0f, dip_35, null);
        } else {
            if (ll_pay.getVisibility() == View.GONE)
                return;
            changeHeight(ll_pay, 1.0f, 0.0f, dip_35, new ChangeEndListner() {
                @Override
                public void end() {
                    ll_pay.setVisibility(View.GONE);
                }
            });
        }

    }

    @OnCheckedChanged(R.id.callcar_type_ss)
    void checkSS(boolean checked) {
        if (checked) {
            presenter.checkSs(true);
        }
    }

    @OnCheckedChanged(R.id.callcar_type_yy)
    void checkYY(boolean checked) {
        if (checked) {
            presenter.checkSs(false);
        }
    }

    @OnCheckedChanged(R.id.channel_taxi)
    void onCheckedTaxi(boolean checked) {
        if (checked)
            presenter.orderTypeChange(Constants.CARTYPE_TAXI);
    }

    @OnCheckedChanged(R.id.channel_specar)
    void onCheckedSpecar(boolean checked) {
        if (checked)
            presenter.orderTypeChange(Constants.CARTYPE_SPECAR);
    }

    @OnCheckedChanged(R.id.channel_specar_soft)
    void onCheckedSpecarSoft(boolean checked) {
        if (checked)
            presenter.orderSpecarTypeChange(0);
    }

    @OnCheckedChanged(R.id.channel_specar_business)
    void onCheckedSpecarBss(boolean checked) {
        if (checked)
            presenter.orderSpecarTypeChange(1);
    }

    @OnCheckedChanged(R.id.channel_specar_haohua)
    void onCheckedSpecarHh(boolean checked) {
        if (checked)
            presenter.orderSpecarTypeChange(2);
    }


    @OnClick(R.id.indexmenu_user)
    public void clickUser() {
        Intent intent = new Intent(this, UserDetailActivity.class);
        goPage(intent);
    }

    @OnClick(R.id.indexmenu_history)
    public void clickHistory() {
        Intent intent = new Intent(this, OrderHistoryActivity.class);
        goPage(intent);
    }

    @OnClick(R.id.indexmenu_wallect)
    public void clickWallect() {
        Intent intent = new Intent(this, WallectActivity.class);
        goPage(intent);
    }

    @OnClick(R.id.indexmenu_setting)
    public void clickSetting() {
        Intent intent = new Intent(this, SettingActivity.class);
        goPage(intent);
    }

    @OnClick(R.id.indexmenu_about)
    public void clickAbout() {
        Intent intent = new Intent(this, AboutActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.indexmenu_callcar)
    public void clickCallcarMenu() {
        dl_menu.closeDrawers();
    }

    @OnClick(R.id.indexmenu_loginorout_con)
    public void clickLout() {
        if (AppManger.getInstance().isLogin()) {
            showLoginOutView();
        } else {
            goLoginPage();
        }
    }

    @OnClick(R.id.indexmenu_callcenter)
    public void clickCallCenter() {
        UIHelper.showCallDialog(this, ModuleUtils.getStrFromResource(this, R.string.phone_custome));
    }

    @OnClick(R.id.title_left)
    public void clickMenu() {
        dl_menu.openDrawer(GravityCompat.START);
    }

    @OnClick(R.id.title_right_tv)
    public void clickLogin() {
        goLoginPage();
    }

    @OnClick(R.id.indexcall_mapshow_location)
    public void clickLocation() {
        presenter.refreshLocType(MainPresenterImpl.MODE_MAP_LOC);
    }

    @OnClick(R.id.indexcall_mapshow_desc)
    public void clickLocDesc() {
        startActivityForResult(PlaceChooseActivity.getDiyIntent(this, presenter.getStartAddr(), true), REQUEST_CODE_START);
    }

    @OnClick(R.id.order_details_date)
    public void clickDate() {
        Intent intent = new Intent(this, OrderDateSelectDialogActivity.class);
        intent.putExtra(OrderDateSelectDialogActivity.EXTRAS_DATE, presenter.getCurrentOrder().getBookDate());
        startActivityForResult(intent, REQUEST_CHOOSE_DATE);
    }

    @OnClick(R.id.order_details_account)
    public void clickPhone() {
        if (!AppManger.getInstance().isLogin()) {
            showTip("请登录后叫车");
            return;
        }
        startActivityForResult(OrderAccountChooseActivity.getDiyIntent(this, presenter.getPsPhone()), REQUEST_CHOOSE_PHONE);
    }

    @OnClick(R.id.order_details_tip)
    public void clickTip() {
        Order currentOrder = presenter.getCurrentOrder();
        String tip = StringUtils.isEmpty(currentOrder.getOrderTip()) ? "0" : currentOrder.getOrderTip();
        startActivityForResult(OrderTipChooseActivity.getDiyIntent(this, Integer.parseInt(tip)), REQUEST_CHOOSE_TIP);
    }

    @OnClick(R.id.order_details_start)
    public void clickStart() {
        AddressInfo info = presenter.getStartAddr();
        startActivityForResult(PlaceChooseActivity.getDiyIntent(this, info, true), REQUEST_CODE_START);
    }

    @OnClick(R.id.order_details_end)
    public void clickEnd() {
        startActivityForResult(PlaceChooseActivity.getDiyIntent(this, presenter.getEndAddr(), true), REQUEST_CODE_END);
    }

    @OnClick(R.id.carcall_call)
    public void clickCall() {
        presenter.beforeCallCar();
    }

    @OnClick(R.id.order_details_pay)
    public void clickYgCost() {
        presenter.showCostDetails();
    }


    @Override
    public MainPresenter createPresenter() {
        return new MainPresenterImpl(this);
    }

    private void setListeners() {
        bdMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                presenter.mapCenterChange(mapStatus.target);
            }
        });
        bdMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                presenter.refreshLocType(MainPresenterImpl.MODE_MAP_DIY);
            }
        });
    }

    private void goPage(Intent intent) {
        if (!AppManger.getInstance().isLogin())
            displayShort(getString(R.string.qingxiandenglu));
        else
            startActivity(intent);
    }

    public interface ChangeEndListner {
        void end();
    }

    private void changeHeight(final View view, float start, final float end, final int height, final ChangeEndListner endListner) {
        ObjectAnimator scr = ObjectAnimator.ofFloat(view, "wdl", start, end);
        scr.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                layoutParams.height = (int) (height * (float) animation.getAnimatedValue());
                view.setLayoutParams(layoutParams);
            }
        });
        scr.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (endListner != null)
                    endListner.end();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        scr.start();
    }

}
